#include "utils.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QDir>
#include <QFontDatabase>

QString Utils::qJsonValueToQString(const QJsonValue &value)
{
    if(value.isArray())
    {
        QJsonDocument doc(value.toArray());
        return doc.toJson(QJsonDocument::Compact);
    }
    else if(value.isObject())
    {
        QJsonDocument doc(value.toObject());
        return doc.toJson(QJsonDocument::Compact);
    }
    else if(value.isBool())
    {
        return value.toBool()?"true":"false";
    }
    else if(value.isDouble())
    {
        return QString("%1").arg(value.toDouble());
    }
    else if(value.isString())
    {
        return value.toString();
    }
    else if(value.isUndefined())
    {
        return "undefined";
    }
    else if(value.isNull())
    {
        return "null";
    }

    return "";
}

QJsonValue Utils::qStringToQJsonValue(const QString str)
{
    QJsonParseError e;
    QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8(),&e);
    if(e.error==QJsonParseError::NoError){
        if(doc.isArray()){
            return doc.array();
        }else if(doc.isObject()){
            return doc.object();
        }
    }

    return QJsonValue();
}

QString Utils::currentDateTime()
{
    return QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
}

QString Utils::currentTime()
{
    return QTime::currentTime().toString("HH:mm:ss");
}

bool Utils::makesurePathExists(const QString &path)
{
    QDir d(path);
    if(d.exists()){
        return true;
    }

    return d.mkpath(d.absolutePath());
}

/*
    设置image图片的背景颜色
*/
void Utils::setImageColor(QImage &image, QColor color)
{
    int w = image.width();
    int h = image.height();
    for(int x=0;x<w;x++){
        for(int y=0;y<h;y++){
            QColor c = image.pixelColor(x,y);
            if(c.alpha()>0){  //alpha大于0代表该像素点是非透明的
                color.setAlpha(c.alpha());
                image.setPixelColor(x,y,color);
            }
        }
    }
}

/*
    将colorStr转化成标准HTML颜色值返回。如果colorStr
    无效，则返回空
*/
QString Utils::toStandardColor(QString colorStr)
{
    QColor retColor;
    if(colorStr.startsWith("rgba"))
    {
        colorStr.replace(" ","");
        colorStr.replace("rgba","");
        colorStr.replace("(","");
        colorStr.replace(")","");

        QStringList list = colorStr.split(',');
        if(list.size() == 4)
        {
            int r = list[0].toInt();
            int g = list[1].toInt();
            int b = list[2].toInt();
            int a = int(list[3].toDouble() * 255 * 1.0);
            retColor.setRgb(r,g,b,a);
        }
    }
    else if(colorStr.startsWith("rgb"))
    {
        colorStr.replace(" ","");
        colorStr.replace("rgb","");
        colorStr.replace("(","");
        colorStr.replace(")","");

        QStringList list = colorStr.split(',');
        if(list.size() == 3)
        {
            int r = list[0].toInt();
            int g = list[1].toInt();
            int b = list[2].toInt();
            retColor.setRgb(r,g,b);
        }
    }
    else if(colorStr.startsWith("#"))
    {
        colorStr.replace(" ","");
        retColor.setNamedColor(colorStr);
    }else{
        retColor.setNamedColor(colorStr);
    }

    if(retColor.isValid()){
        return retColor.name(QColor::HexArgb);
    }else{
        return "";
    }
}

/*
    遍历dir中符合filters的所有文件/文件夹并返回

    dir：需要遍历的目录
    filters：文件类型过滤器
    depth：遍历深度
*/
void __listDir(QDir dir,bool recursion, QVector<QFileInfo>& files){
    QFileInfoList fileInfoList = dir.entryInfoList();
    if(fileInfoList.empty()){
        return ;
    }

    int i=0;
    do
    {
        QFileInfo fileInfo = fileInfoList.at(i);
        if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
        {
            ++i;
            continue;
        }

        files.push_back(fileInfo);

        if(fileInfo.isDir() && recursion)
        {
            __listDir(QDir(fileInfo.absoluteFilePath()),recursion,files);
        }

        ++i;
    }while(i<fileInfoList.size());

}
QVector<QFileInfo> Utils::listDir(QDir dir, bool recursion)
{
    QVector<QFileInfo> retFileInfos;
    if(!dir.exists()){
        return retFileInfos;
    }

    __listDir(dir,recursion,retFileInfos);

    return retFileInfos;

}


bool Utils::hasFont(const QString &font)
{
    QFontDatabase fontDb;
    return fontDb.hasFamily(font);
}

QVector<int> Utils::randomNum(int min,int max, int count)
{
    if(max<0){
        max=0;
    }

    QVector<int> rets;
    for(int i=0;i<count;i++){
        int value=qrand()%(max+1);
        if(value<min){
            value=min+qrand()%(max-min);
        }
        rets.push_back(value);
    }

    return rets;
}
